//
//  MBForumDetailViewController.m
//  MiBaoTu
//
//  Created by admin on 16/10/17.
//  Copyright © 2016年 com.caesartech15. All rights reserved.
//

#import "MBForumDetailViewController.h"
#import <WebKit/WebKit.h>
#import "MBForumShowCommentViewController.h"
#import "MBLoginController.h"

#import "MBForumDetailHeaderView.h"
#import "MBForumDetailCell.h"
#import "AttentionView.h"
#import "EmojiView.h"

@interface MBForumDetailViewController ()<UIWebViewDelegate,UITableViewDataSource,UITableViewDelegate,MBForumDetailCellDelegate,MBForumDetailHeaderViewDelegate,AttentionViewDelegate,UITextFieldDelegate,EmojiViewDelegate> {
    UIScrollView                    *_scrollView;
    MBForumDetailHeaderView         *_headerView;
    UIWebView                       *_webView;
    UITableView                     *_tableView;
    
    UIView                          *_bottomView;
    UILabel                         *_zanLb;
    UIImageView                     *imgViewLeft;
    
    UIView                          *_inputView;
    UITextField                     *_inputField;
    UIButton                        *sureBt;
    UIView                          *_showderView;
    float                          inputTime;
    
    NSMutableArray                  *_mutArr;
    NSMutableArray                  *_mutHeightArr; //高度
    int                             page;
    NSMutableDictionary             *_replyMutDic;
    
    EmojiView                       *_emojiView;
    UIButton                        *emojiBt;
}

@end
@implementation MBForumDetailViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
     [self registerForKeyboardNotifications];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self removeForKeyboardNotifications];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _mutArr = [[NSMutableArray alloc]init];
    _mutHeightArr = [[NSMutableArray alloc]init];
    _replyMutDic = [[NSMutableDictionary alloc]init];
    
    [self setNavBar];
    
    [self onCreateUI];
    
    [self onLoadNew];
    
    [self updateForumNum];
    
}

#pragma mark - UI
- (void)setNavBar
{
    [self setTitleView:[_dataDic objectForKey:@"Title"]];
    
    [self setBackItem];
}

- (void)onCreateUI
{
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.view.height)];
    _scrollView.backgroundColor = [UIColor clearColor];
    _scrollView.scrollEnabled = NO;
    
    if (!_headerView) {
        if (!ISIPAD) {
                 _headerView = [[MBForumDetailHeaderView alloc]initWithFrame:CGRectMake(0, 0, _scrollView.width, 120*PERCEN)];
        }
        else{
                   _headerView = [[MBForumDetailHeaderView alloc]initWithFrame:CGRectMake(460*PERCEN, 0, _scrollView.width-2*460*PERCEN, 140*PERCEN)];
        }
      
        _headerView.delegate = self;
    }
    _headerView.dataDic = self.dataDic;
    _headerView.isActivity = self.isActivity;
    [_scrollView addSubview:_headerView];
    
//    NSString *str = [NSString stringWithFormat:@"<p>今天和Emily一起去海洋馆玩了，很累，不过很开心！非常值得，期待下次的亲子秀活动。等等上面都是废话，请别介意。今天和Emily一起去海洋馆玩了，很累，不过很开心！非常值得，期待下次的亲子秀活动。等等上面都是废话，请别介意。</p><img src=\"%@\" alt=\"1.png\" align=\"middle\" margin=\"0 auto\" display=\"block\" width=\"100%%\"><p>今天和Emily一起去海洋馆玩了，很累，不过很开心！非常值得，期待下次的亲子秀活动。等等上面都是废话，请别介意.今天和Emily一起去海洋馆玩了，很累，不过很开心！非常值得，期待下次的亲子秀活动。等等上面都是废话，请别介意。今天和Emily一起去海洋馆玩了，很累，不过很开心！非常值得，期待下次的亲子秀活动。等等上面都是废话，请别介意。<p>今天和Emily一起去海洋馆玩了，很累，不过很开心！非常值得，期待下次的亲子秀活动。等等上面都是废话，请别介意。今天和Emily一起去海洋馆玩了，很累，不过很开心！非常值得，期待下次的亲子秀活动。等等上面都是废话，请别介意。今天和Emily一起去海洋馆玩了，很累，不过很开心！非常值得，期待下次的亲子秀活动。等等上面都是废话，请别介意。",@"http://mbt.hzxgroup.com/upload/124/20161018/90390c710029ce6b861910f56a08ede6.png"];
    NSMutableString *content = [NSMutableString stringWithFormat:@"%@",[_dataDic objectForKey:@"Content"]];
    NSMutableArray  *imgContentArr = [[NSMutableArray alloc]init];
    if (_isActivity == YES) {
     
        NSMutableString *contMutStr = [[NSMutableString alloc]initWithFormat:@"%@",content];
        NSMutableArray *picArr = [[NSMutableArray alloc]init];
        [contMutStr replaceOccurrencesOfString:@"<p>" withString:@"" options:1 range:NSMakeRange(0, contMutStr.length)];
        [contMutStr replaceOccurrencesOfString:@"</p>" withString:@"\n" options:1 range:NSMakeRange(0, contMutStr.length)];
        [contMutStr replaceOccurrencesOfString:@"<br/>" withString:@"\n" options:1 range:NSMakeRange(0, contMutStr.length)];
        NSArray *contentArr = [contMutStr componentsSeparatedByString:@"<img src="];
        for (NSString *picStr in contentArr) {
            if ([picStr containsString:@" title="]) {
                //纯图片
                NSArray *picUrlArr = [picStr componentsSeparatedByString:@" title="];
                NSMutableString *picUrlStr = [NSMutableString stringWithString:picUrlArr[0]];
                if (picUrlStr.length > 0) {
                    [picUrlStr replaceOccurrencesOfString:@"\"" withString:@"" options:1 range:NSMakeRange(0, picUrlStr.length)];
                    [picArr addObject:picUrlStr];
                }
                if ([picUrlStr containsString:@"\"/>"]) {
                    NSArray *picContentArr = [picUrlStr componentsSeparatedByString:@"\"/>"];
                    [contMutStr appendString:picContentArr[1]];
                }
            } else {
                [contMutStr appendString:picStr];
            }
        }
        
        for (NSString *showContent in picArr) {
            if ([showContent rangeOfString:@".png"].location != NSNotFound ||
                [showContent rangeOfString:@".PNG"].location != NSNotFound ||
                [showContent rangeOfString:@".jpg"].location != NSNotFound ||
                [showContent rangeOfString:@".JPG"].location != NSNotFound ||
                [showContent rangeOfString:@".jpeg"].location != NSNotFound ||
                [showContent rangeOfString:@".JPEG"].location != NSNotFound) {
                //添加图片
                NSMutableString *imgStr = [NSMutableString stringWithFormat:@"%@",showContent];
//                [imgStr insertString:[NSString stringWithFormat:@"%@",MUSIC_PLAY_Url] atIndex:0];
                [imgContentArr addObject:imgStr];
            }
        }
    } else {
        
        NSArray *contentArr = [content componentsSeparatedByString:@"\n"];
        
        if (contentArr.count == 1) {
            contentArr = [content componentsSeparatedByString:@"<img"];
            for (NSString *showContent in contentArr) {
                if ([showContent containsString:@"width=\"100%\">"]) {
                    NSArray *nArr = [showContent componentsSeparatedByString:@"width=\"100%\">"];
                    
                    //添加图片
                    if ([nArr[0] hasPrefix:@" src = "]) {
                        NSMutableString *imgStr = [NSMutableString stringWithFormat:@"%@",nArr[0]];
                        [imgStr replaceOccurrencesOfString:@" src = " withString:@"" options:1 range:NSMakeRange(0, imgStr.length)];
                        [imgStr replaceOccurrencesOfString:@" src=\"" withString:@"" options:1 range:NSMakeRange(0, imgStr.length)];
                        [imgStr replaceOccurrencesOfString:@"'/" withString:@"" options:1 range:NSMakeRange(0, imgStr.length)];
                        [imgStr replaceOccurrencesOfString:@"png " withString:@"png" options:1 range:NSMakeRange(0, imgStr.length)];
                        [imgStr replaceOccurrencesOfString:@"PNG " withString:@"PNG" options:1 range:NSMakeRange(0, imgStr.length)];
                        [imgStr replaceOccurrencesOfString:@"jpg " withString:@"jpg" options:1 range:NSMakeRange(0, imgStr.length)];
                        [imgStr replaceOccurrencesOfString:@"JPG " withString:@"JPG" options:1 range:NSMakeRange(0, imgStr.length)];
                        [imgStr replaceOccurrencesOfString:@"jpeg " withString:@"jpeg" options:1 range:NSMakeRange(0, imgStr.length)];
                        [imgStr replaceOccurrencesOfString:@"JPEG " withString:@"JPEG" options:1 range:NSMakeRange(0, imgStr.length)];
                        [imgStr insertString:[NSString stringWithFormat:@"/"] atIndex:0];
                        [imgContentArr addObject:imgStr];
                    }
                }
            }
        }
        else {
    }
        
        for (NSString *showContent in contentArr) {
            if ([showContent hasPrefix:@"<img"]) {
                //添加图片
                NSMutableString *imgStr = [NSMutableString stringWithFormat:@"%@",showContent];
                [imgStr replaceOccurrencesOfString:@"<img src = " withString:@"" options:1 range:NSMakeRange(0, imgStr.length)];
                [imgStr replaceOccurrencesOfString:@"'/" withString:@"" options:1 range:NSMakeRange(0, imgStr.length)];
                [imgStr replaceOccurrencesOfString:@" width=\"100%\">" withString:@"" options:1 range:NSMakeRange(0, imgStr.length)];
                [imgStr insertString:[NSString stringWithFormat:@"/"] atIndex:0];
                [imgContentArr addObject:imgStr];
            }
        }
    }
    
    //图片地址替换成完整的
    for (NSString *imgStr in imgContentArr) {
        NSString *newImgStr = [NSString stringWithFormat:@"%@%@",MUSIC_PLAY_Url,imgStr];
        NSRange range = [content rangeOfString:imgStr];
        if (range.length == 0) {
            //处理 jpeg
            if ([imgStr rangeOfString:@".jpeg"].location != NSNotFound) {
                NSString *nimgStr = [[imgStr componentsSeparatedByString:@".jpeg"]firstObject];
                range = [content rangeOfString:nimgStr];
                if (range.length > 0) {
                    range = NSMakeRange(range.location, range.length+5);
                }
            }
            else if ([imgStr rangeOfString:@".JPEG"].location != NSNotFound) {
                NSString *nimgStr = [[imgStr componentsSeparatedByString:@".JPEG"]firstObject];
                range = [content rangeOfString:nimgStr];
                if (range.length > 0) {
                    range = NSMakeRange(range.location, range.length+5);
                }
            }
        }
        if (range.length > 0) {
            [content replaceCharactersInRange:range withString:newImgStr];
            if (_isActivity == YES) {
                //活动 就添加宽度
                [content insertString:@" width=\"100%\"" atIndex:range.location+newImgStr.length+1];
            }
        }
    }
    
    _webView = [[UIWebView alloc]initWithFrame:CGRectMake(ISIPAD?460*PERCEN:0, _headerView.bottom, _scrollView.width, 0)];
    if (ISIPAD) {
        _webView.frame=CGRectMake(460*PERCEN, _headerView.bottom+20*PERCEN, SCREEN_WIDTH-2*460*PERCEN, 0);
    }
    _webView.backgroundColor = [UIColor greenColor];
    if (ISIPAD) {
         _webView.backgroundColor = [UIColor whiteColor];
    }
    _webView.delegate = self;
    _webView.scrollView.scrollEnabled = NO;
    _webView.scrollView.contentSize = CGSizeMake(_webView.width, _webView.height);
    [_webView sizeToFit];
    [_scrollView addSubview:_webView];
    NSString * htmlcontent = [NSString stringWithFormat:@"<div id=\"webview_content_wrapper\">%@</div>", content];
    [_webView loadHTMLString:htmlcontent baseURL:nil];
    
    //bottom
    _bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, _webView.bottom, _scrollView.width, 70*PERCEN)];
    if (ISIPAD) {
        _bottomView.frame=CGRectMake(_webView.left, _webView.bottom, _webView.width, 110*PERCEN);
        _bottomView.backgroundColor=[UIColor cyanColor];
    }
    _bottomView.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:_bottomView];
    
    //zan
    UIImage *imgLeft1 = [UIImage imageNamed:@"zan1"];
    UIImage *imgLeft2 = [UIImage imageNamed:@"zan2"];
    imgViewLeft = [[UIImageView alloc]initWithFrame:CGRectMake(25*PERCEN, (_bottomView.height-imgLeft1.size.height)/2., imgLeft1.size.width, imgLeft1.size.height)];
    if (ISIPAD) {
        imgViewLeft.frame=CGRectMake(20*PERCEN, 40*PERCEN, imgLeft1.size.width, imgLeft1.size.height);
    }
    imgViewLeft.image = (_isParise ? imgLeft2 : imgLeft1);
    [_bottomView addSubview:imgViewLeft];
    
    _zanLb = [[UILabel alloc]initWithFrame:CGRectMake(imgViewLeft.right+5, (_bottomView.height-20)/2., 200, 20)];
    if (ISIPAD) {
        _zanLb.frame=CGRectMake(imgViewLeft.right+10*PERCEN , 40*PERCEN, 400*PERCEN, 26*PERCEN);
    }
    _zanLb.backgroundColor = [UIColor clearColor];
    _zanLb.textAlignment = NSTextAlignmentLeft;
    _zanLb.textColor = (_isParise?TINK_COLOR:UIColorFromHex(0x999999));
    _zanLb.font = [UIFont systemFontOfSize:13.f];
    if (ISIPAD) {
         _zanLb.font = [UIFont systemFontOfSize:26*PERCEN];
    }
    _zanLb.text = [[NSString stringWithFormat:@"%@",[_dataDic objectForKey:@"PraiseNum"]] getValues];
    [_bottomView addSubview:_zanLb];
    
    UIButton *zanBt = [UIButton buttonWithType:UIButtonTypeCustom];
    zanBt.frame = CGRectMake(imgViewLeft.left, 0, 120, _bottomView.height);
    if (ISIPAD) {
         zanBt.frame = CGRectMake(imgViewLeft.left, 40*PERCEN, 240*PERCEN, 40*PERCEN);
         
    }
    zanBt.backgroundColor = [UIColor clearColor];
    [zanBt addTarget:self action:@selector(onSelectBtForZan) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView addSubview:zanBt];
    
    //评论
    UIButton *pinLunBt = [UIButton buttonWithType:UIButtonTypeCustom];
    pinLunBt.frame = CGRectMake(_bottomView.width-25*PERCEN-120*PERCEN, 0, 120*PERCEN, _bottomView.height);
    pinLunBt.backgroundColor = [UIColor clearColor];
    [pinLunBt setTitle:@"评论" forState:UIControlStateNormal];
    [pinLunBt setTitle:@"评论" forState:UIControlStateHighlighted];
    [pinLunBt setTitleColor:UIColorFromHex(0x999999) forState:UIControlStateNormal];
    [pinLunBt setTitleColor:UIColorFromHex(0x999999) forState:UIControlStateHighlighted];
    pinLunBt.titleLabel.font = _zanLb.font;
    [pinLunBt setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    [pinLunBt setImage:[UIImage imageNamed:@"pinglun"] forState:UIControlStateNormal];
    [pinLunBt setImage:[UIImage imageNamed:@"pinglun"] forState:UIControlStateHighlighted];
    [pinLunBt setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 25)];
    [pinLunBt addTarget:self action:@selector(onSelectBtForPinLun) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView addSubview:pinLunBt];
    _scrollView.height = _bottomView.bottom;
    
    [self addBottomUI];
}

- (void)addBottomUI
{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.view.height) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    _tableView.tableHeaderView = _scrollView;
    [_tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(onLoadNew)];
//    [_tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(onLoadMore)];
    
    //键盘
    _inputView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 40)];
    _inputView.backgroundColor = UIColorFromHex(0xf5f5f5);
    _inputView.hidden = YES;
    [[UIApplication sharedApplication].keyWindow addSubview:_inputView];
    
    emojiBt = [UIButton buttonWithType:UIButtonTypeCustom];
    emojiBt.backgroundColor = [UIColor clearColor];
    emojiBt.frame = CGRectMake(0, 0, 50, _inputView.height);
    [emojiBt setImage:[UIImage imageNamed:@"emoji"] forState:UIControlStateNormal];
    [emojiBt setImage:[UIImage imageNamed:@"emoji"] forState:UIControlStateNormal];
    [emojiBt setImageEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 5)];
    [emojiBt addTarget:self action:@selector(onSelectEmojiAction:) forControlEvents:UIControlEventTouchUpInside];
    [_inputView addSubview:emojiBt];
    
    _inputField = [[UITextField alloc]initWithFrame:CGRectMake(50, 5, _inputView.width-50-50, 30)];
    _inputField.backgroundColor = [UIColor whiteColor];
    _inputField.placeholder = @"填写评论";
    _inputField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _inputField.delegate = self;
    _inputField.font = [UIFont systemFontOfSize:13];
    [_inputField setValue:[UIFont systemFontOfSize:13]forKeyPath:@"_placeholderLabel.font"];
    [_inputField resignFirstResponder];
    [_inputView addSubview:_inputField];
    
    sureBt = [UIButton buttonWithType:UIButtonTypeCustom];
    sureBt.backgroundColor = [UIColor clearColor];
    sureBt.frame = CGRectMake(_inputView.width - 50, 0, 50, _inputView.height);
    [sureBt setTitle:@"发送" forState:UIControlStateNormal];
    [sureBt setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    sureBt.titleLabel.font = [UIFont systemFontOfSize:13.f];
    [sureBt addTarget:self action:@selector(onSelectSureAction) forControlEvents:UIControlEventTouchUpInside];
    [_inputView addSubview:sureBt];
    
    _showderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 216 - 40)];
    _showderView.backgroundColor = [UIColorFromHex(0x000000) colorWithAlphaComponent:.2];
    _showderView.hidden = YES;
    _showderView.userInteractionEnabled = YES;
    [[UIApplication sharedApplication].keyWindow addSubview:_showderView];
    
    //表情
    _emojiView = [[EmojiView alloc]init];
    _emojiView.delegate = self;
    [[UIApplication sharedApplication].keyWindow addSubview:_emojiView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onTapHideInputAction)];
    [_showderView addGestureRecognizer:tap];
}

#pragma mark - 加载数据接口
- (void)onLoadNew
{
    page = 1;
    [self onLoadData];
}

- (void)onLoadMore
{
//    ++page;
//    [self onLoadData];
    NSLog(@"****");
}

- (void)onLoadData
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:FORUM_DETAIL_INFO_URL_PATH,[_dataDic objectForKey:@"ID"],[NSNumber numberWithInt:page]] view:nil success:^(NSDictionary *json) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [_tableView.header endRefreshing];
        [_tableView.footer endRefreshing];
        
        if ([json isKindOfClass:[NSDictionary class]]) {
            if ([json[@"ret_code"] integerValue]==0) {
                NSArray *arr = json[@"data"];
                if (page == 1) {
                    [_mutArr removeAllObjects];
                }
                
                if ([arr isKindOfClass:[NSArray class]]) {
                    if (arr.count > 0) {
                        //调整返回数据
                        [self onSetUpReplyData:arr];
                        
                        [self onLoadDataForHeight];
                    }
                }
            }
            [_tableView reloadData];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [_tableView.header endRefreshing];
        [_tableView.footer endRefreshing];
    }];

}

//调整返回数据
- (void)onSetUpReplyData:(NSArray *)arr
{
    for (NSDictionary *dictionary in arr) {
        NSArray *array = [dictionary objectForKey:@"ReplyInfo"];
        if ([array isKindOfClass:[NSArray class]]) {
            if (array.count > 0) {
                //存有回复内容,先存评论内容
                NSMutableDictionary *mutDic = [[NSMutableDictionary alloc]initWithDictionary:dictionary];
                [mutDic setObject:@{} forKey:@"ReplyInfo"];
                [_mutArr addObject:mutDic];
                
                for (NSDictionary *dic in array) {
                    NSMutableDictionary *mutDic = [[NSMutableDictionary alloc]initWithDictionary:dictionary];
                    [mutDic setObject:dic forKey:@"ReplyInfo"];
                    [_mutArr addObject:mutDic];
                }
            } else {
                //没有回复内容
                NSMutableDictionary *mutDic = [[NSMutableDictionary alloc]initWithDictionary:dictionary];
                [mutDic setObject:@{} forKey:@"ReplyInfo"];
                [_mutArr addObject:mutDic];
            }
        } else {
            //没有回复内容
            NSMutableDictionary *mutDic = [[NSMutableDictionary alloc]initWithDictionary:dictionary];
            [mutDic setObject:@{} forKey:@"ReplyInfo"];
            [_mutArr addObject:mutDic];
        }
    }
}

//计算评论内容高度
- (void)onLoadDataForHeight
{
    [_mutHeightArr removeAllObjects];
    
    NSMutableParagraphStyle *paragraphHui = [[NSMutableParagraphStyle alloc]init];
    paragraphHui.lineSpacing = 6*PERCEN;
    
    for (NSDictionary *dictionary in _mutArr) {
        NSDictionary *dic = [dictionary objectForKey:@"ReplyInfo"];
        if ([dic isKindOfClass:[NSDictionary class]]) {
            NSString *reply;
            if (dic.allKeys.count == 0) {
                //没有回复内容
                NSString *str1 = [NSString stringWithFormat:@"%@",[dictionary objectForKey:@"NickName"]];//@"Karna的爸爸";
                NSString *str2 = [[NSString stringWithFormat:@"%@",[dictionary objectForKey:@"Content"]]replaceUnicode];//@"照片拍的不错，给你个赞！";
                reply = [NSString stringWithFormat:@"%@: %@",str1,str2];
                
            } else {
                //有回复内容
                NSString *str0 = @"回复";
                NSString *Str1 = [NSString stringWithFormat:@"%@",[dic objectForKey:@"ReplyName"]];//@"Karna";
                NSString *Str2 = [NSString stringWithFormat:@"%@",[dic objectForKey:@"RepliedName"]];//@"Karna的爸爸";
                NSString *str3 = [[NSString stringWithFormat:@"%@",[dic objectForKey:@"ReplyCont"]] replaceUnicode];//@"照片拍的不错，给你个赞！照片拍的不错，给你个赞！照片拍的不错，给你个赞！照片拍的不错，给你个赞！照片拍的不错，给你个赞！";
                
                reply = [NSString stringWithFormat:@"%@ %@: %@ %@",Str1,str0,Str2,str3];
                
            }
            
            if (reply.length > 0) {
                
                NSMutableAttributedString *nickAttr = [[NSMutableAttributedString alloc]initWithString:reply];
                [nickAttr addAttribute:NSParagraphStyleAttributeName value:paragraphHui range:NSMakeRange(0, reply.length)];
                
                float nickHeight = [nickAttr boundingRectWithSize:CGSizeMake(SCREEN_WIDTH-2*25*PERCEN, 1000) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading context:nil].size.height;
                nickHeight = (nickHeight / 20. + 1) * 20.;
                [_mutHeightArr addObject:[NSNumber numberWithFloat:(nickHeight+10)]];
            }
        }
        
    }
}

//查看次数
- (void)updateForumNum
{
    [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:FORUM_VIEW_NUM_URL_PATH,[_dataDic objectForKey:@"ID"]] view:nil success:^(NSDictionary *json) {
       //不管结果好坏
        if (_finishBlock) {
            _finishBlock(@"ViewNum",_dataDic);
        }
    } failure:^(NSError *error) {
      
    }];
}

#pragma mark - 赞
- (void)onSelectBtForZan
{
    if (![UserManager standerDefult].userModel.UserID) {
        MBLoginController *registerLastVC = [[MBLoginController alloc] init];
        registerLastVC.formBaseViewCtrl = NSStringFromClass([self class]);
        [self.navigationController pushViewController:registerLastVC animated:YES];
        return;
    }
    
    if (![_dataDic isKindOfClass:[NSDictionary class]]) return;
    UserModel *model = [UserManager standerDefult].userModel;
    if (!model) return;
    
    //区分点赞或取消点赞
    NSString *idStr = [NSString stringWithFormat:@"%@",[_dataDic objectForKey:@"ID"]];
    UIImage *imgLeft1 = [UIImage imageNamed:@"zan1"];
    UIImage *imgLeft2 = [UIImage imageNamed:@"zan2"];
    NSMutableDictionary *mutDic = [[NSMutableDictionary alloc]initWithDictionary:_dataDic];
    if (_isParise == YES) {
        //取消点赞
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:FORUM_CANCEL_ZAN_URL_PATH,model.UserID,[_dataDic objectForKey:@"ID"],@2] view:nil success:^(id json) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            if ([json[@"ret_code"] integerValue]==0) {
                //取消点赞成功
                _isParise = NO;
                imgViewLeft.image = (_isParise ? imgLeft2 : imgLeft1);
                _zanLb.textColor = (_isParise?TINK_COLOR:UIColorFromHex(0x999999));
                
                //保存数据库
                FMManageObject *managerFM = [FMManageObject standerDefault];
                NSArray *idArr = [managerFM SelectTableByPraiseWithContentID:idStr];
                if (idArr.count != 0) {
                    [managerFM deleteByPraiseFileID:idStr];
                }
                [managerFM insertOnShowPraiseTableWithId:idStr withIsPraise:@"0"];
                [mutDic setValue:[NSNumber numberWithInt:([[_dataDic objectForKey:@"PraiseNum"] intValue]-1)] forKey:@"PraiseNum"];
                _dataDic = mutDic;
                _zanLb.text = [[NSString stringWithFormat:@"%@",[mutDic objectForKey:@"PraiseNum"]] getValues];
                
                if (_finishBlock) {
                    _finishBlock(@"cancel_zan",@{@"isParise":@"0",@"id":idStr});
                }
            } else {
                [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
            }
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }];
    } else  {
        //点赞
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:FORUM_ZAN_URL_PATH,model.UserID,[_dataDic objectForKey:@"ID"],@2] view:nil success:^(id json) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            if ([json[@"ret_code"] integerValue]==0) {
                //点赞成功
                _isParise = YES;
                imgViewLeft.image = (_isParise ? imgLeft2 : imgLeft1);
                _zanLb.textColor = (_isParise?TINK_COLOR:UIColorFromHex(0x999999));
                
                //保存数据库
                FMManageObject *managerFM = [FMManageObject standerDefault];
                NSArray *idArr = [managerFM SelectTableByPraiseWithContentID:idStr];
                if (idArr.count != 0) {
                    [managerFM deleteByPraiseFileID:idStr];
                }
                [managerFM insertOnShowPraiseTableWithId:idStr withIsPraise:@"1"];
                [mutDic setValue:[NSNumber numberWithInt:([[_dataDic objectForKey:@"PraiseNum"] intValue]+1)] forKey:@"PraiseNum"];
                _dataDic = mutDic;
                _zanLb.text = [[NSString stringWithFormat:@"%@",[_dataDic objectForKey:@"PraiseNum"]] getValues];
                
                if (_finishBlock) {
                    _finishBlock(@"zan",@{@"isParise":@"1",@"id":idStr});
                }
            } else {
                [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
            }
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }];
    }
}

#pragma mark - 评论
- (void)onSelectBtForPinLun
{
    if (_mutArr.count > 0) {
        [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
    [_replyMutDic removeAllObjects];
    _emojiView.alpha = 0;
    emojiBt.selected = NO;
    [_inputField becomeFirstResponder];
}

#pragma mark - 查看更多评论
- (void)onSelectItemForSeeCommentData:(NSDictionary *)value
{
    if ([value isKindOfClass:[NSDictionary class]]) {        
        MBForumShowCommentViewController *show = [[MBForumShowCommentViewController alloc]init];
        show.dataDic = value;
        show.titleStr = [_dataDic objectForKey:@"Title"];
        [self.navigationController pushViewController:show animated:YES];
    }
}

#pragma mark - 回复
- (void)onSelectItemForGetCommentData:(NSDictionary *)value
{
    if ([value isKindOfClass:[NSDictionary class]]) {
        [_replyMutDic removeAllObjects];
        [_replyMutDic addEntriesFromDictionary:value];
    }
    
    //响应键盘
    if (_inputField) {
        _emojiView.alpha = 0;
        emojiBt.selected = NO;
        [_inputField becomeFirstResponder];
    }
}

- (void)onSelectSureAction
{
    if (_inputField.text.length == 0) {
        return;
    }
    
     [self onTapHideInputAction];
    
    UserModel *model = [UserManager standerDefult].userModel;
    if (!model.UserID) {
        MBLoginController *registerLastVC = [[MBLoginController alloc] init];
        registerLastVC.formBaseViewCtrl = NSStringFromClass([self class]);
        [self.navigationController pushViewController:registerLastVC animated:YES];
        return;
    }
    
    if (_replyMutDic.allKeys.count > 0) {
        //有值，表示是回复
        NSString *text = _inputField.text;
        
        NSString *uniStr = [NSString stringWithUTF8String:[text UTF8String]];
        NSData *uniData = [uniStr dataUsingEncoding:NSNonLossyASCIIStringEncoding];
        NSString *goodStr = [[NSString alloc] initWithData:uniData encoding:NSUTF8StringEncoding] ;
        
        NSString*url=[NSString stringWithFormat:FORUM_REPLY_INFO_URL_PATH,model.UserID,[_replyMutDic objectForKey:@"ID"],[_replyMutDic objectForKey:@"UserID"],goodStr];
        
        NSLog(@"url==%@",url);
        
        [[HTTPManager standerDefault]AFGetRequest:url view:nil success:^(id json) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            if ([json[@"ret_code"] integerValue]==0) {
                NSDate *date = [NSDate date];
                
                NSDictionary *nDic = @{@"ComID":[_replyMutDic objectForKey:@"ID"],
                                       @"CreateTime":[NSString stringWithFormat:@"%.f",[date timeIntervalSince1970]],
                                       @"ID":@"1",
                                       @"RepliedName":[_replyMutDic objectForKey:@"NickName"],
                                       @"ReplyCont":text,
                                       @"ReplyName":model.NickName,
                                       @"ToUserID":[_replyMutDic objectForKey:@"UserID"],
                                       @"UserID":model.UserID};
                NSMutableDictionary *mutDic = [[NSMutableDictionary alloc]initWithDictionary:_replyMutDic];
                [mutDic setValue:nDic forKey:@"ReplyInfo"];
                int indexDic = (int)[_mutArr indexOfObject:_replyMutDic];
                //从选中的楼层中插入数据，数据显示在回复最底层
                indexDic = [self getReplyCengByData:(indexDic+1)];
                
                if (indexDic <= _mutArr.count && indexDic >= 0) {
                    [_mutArr insertObject:mutDic atIndex:indexDic];
                    
                    //高度自定义
                    [self onLoadDataForHeight];
                    _inputField.text = @"";
                    [_tableView reloadData];
                } else {
                    [self onLoadNew];
                }
                [_replyMutDic removeAllObjects];
                
            _inputField.text=@"";
            } else {
                [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
            }
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }];
    } else {
        //无值，表示是评论
        NSString *text = _inputField.text;
        NSString *uniStr = [NSString stringWithUTF8String:[text UTF8String]];
        NSData *uniData = [uniStr dataUsingEncoding:NSNonLossyASCIIStringEncoding];
        NSString *goodStr = [[NSString alloc] initWithData:uniData encoding:NSUTF8StringEncoding] ;
        NSString*url=[NSString stringWithFormat:FORUM_COMMENT_INFO_URL_PATH,model.UserID,[_dataDic objectForKey:@"UserID"],[_dataDic objectForKey:@"ID"],goodStr,@2,(_isActivity == YES ? @2:@1)];
        NSLog(@"url==%@",url);
        [[HTTPManager standerDefault]AFGetRequest:url view:nil success:^(id json) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            if ([json[@"ret_code"] integerValue]==0) {
                _inputField.text = @"";
                [self onLoadNew];
            } else {
                [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
            }
            
            _inputField.text=@"";
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }];
    }
}

//从选中的楼层中插入数据，数据显示在回复最底层
- (int)getReplyCengByData:(int)selectIndex
{
    if (selectIndex < _mutArr.count && selectIndex >= 0) {
        for (int i = selectIndex;i < _mutArr.count; i++) {
            NSDictionary *dictionary = [_mutArr objectAtIndex:i];
            NSDictionary *dic = [dictionary objectForKey:@"ReplyInfo"];
            if ([dic isKindOfClass:[NSDictionary class]]) {
                if (dic.allKeys.count == 0) {
                    return i;
                }
            }
        }
        
        return (int)_mutArr.count;
    }
    else if (selectIndex == _mutArr.count+1) {
        //最后一个没有回复的评论
        return selectIndex;
    }
    return -1;
}

- (void)onTapHideInputAction
{
    [_inputField resignFirstResponder];
    _emojiView.alpha = 0 ;
    emojiBt.selected = NO;
    [self onAnimationWithInputView:YES WithHeight:0 WithDuration:inputTime];
}

- (void)registerForKeyboardNotifications
{
    //使用NSNotificationCenter 鍵盤出現時
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWasShow:)
     
                                                 name:UIKeyboardWillShowNotification object:nil];
    
    //使用NSNotificationCenter 鍵盤隐藏時
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWillBeHidden:)
     
                                                 name:UIKeyboardWillHideNotification object:nil];
    
    
}

- (void)removeForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWasShow:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    float keyboardhight = 0;
    if(kbSize.height == 216)
    {
        keyboardhight = 0;
    }
    else
    {
        keyboardhight = kbSize.height-216;   //258 - 216 系统键盘的两个不同高度
    }
    //输入框位置动画加载
    inputTime = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    _emojiView.alpha = 0;
    emojiBt.selected = NO;
    [self onAnimationWithInputView:NO WithHeight:keyboardhight WithDuration:inputTime];
}

//当键盘隐藏的时候
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    //do something
    [self onAnimationWithInputView:YES WithHeight:0 WithDuration:inputTime];
}

-(void)textViewDidEndEditing:(UITextView *)textView
{
    [self onAnimationWithInputView:YES WithHeight:0 WithDuration:inputTime];
    
    //释放
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}


//输入框和遮挡层动画效果
- (void)onAnimationWithInputView:(BOOL)isHidden WithHeight:(float)heght WithDuration:(float)time
{
    [UIView animateWithDuration:time animations:^{
        if (_emojiView.alpha == 0) {
            emojiBt.selected = NO;
            _emojiView.top = SCREEN_WIDTH;
            _inputView.top = (isHidden == YES ? SCREEN_HEIGHT : SCREEN_HEIGHT-216-heght-40);
            _inputView.hidden = isHidden;
            _showderView.hidden = isHidden;
            _showderView.height = _inputView.top;
        } else {
            emojiBt.selected = YES;
            _emojiView.top = SCREEN_HEIGHT - 216;
            _inputView.top = _emojiView.top-40;
            _inputView.hidden = NO;
            _showderView.height = _inputView.top;
            _showderView.hidden = NO;
        }
        
    } completion:^(BOOL finished) {
        if (finished) {
          //  _inputField.text = @"";
        }
    }];
}

#pragma mark -表情
- (void)onSelectEmojiAction:(UIButton *)bt
{
    if (bt.selected == NO) {
        _emojiView.alpha = 1.f;
        [_inputField resignFirstResponder];
    } else {
        _emojiView.alpha = 0.f;
        [_inputField becomeFirstResponder];
    }
    
//    bt.selected = !bt.selected;
}

#pragma mark -删除个人活动
- (void)onSelectItemForDeleteUserActivityWithValue:(NSDictionary *)value
{
    if ([value isKindOfClass:[NSDictionary class]]) {
        AttentionView *_attention = [[AttentionView alloc]initWithTitle:[NSString stringWithFormat:@"是否确认删除话题《%@》?",[value objectForKey:@"Title"]] withCancelBt:@"确认" withSureBt:@"取消"];
        _attention.delegate = self;
        _attention.orientation = self.orientation;
        _attention.dataDic = value;
        [_attention showInWindow];
    }
}

- (void)onSelectSureItem:(AttentionView *)view
{
}
- (void)onSelectCancelItem:(AttentionView *)view
{
    //删除
    UserModel *model = [UserManager standerDefult].userModel;
    if (!model.UserID) {
        MBLoginController *registerLastVC = [[MBLoginController alloc] init];
        registerLastVC.formBaseViewCtrl = NSStringFromClass([self class]);
        [self.navigationController pushViewController:registerLastVC animated:YES];
        return;
    }
    
    NSDictionary *dic = view.dataDic;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    if (dic.allKeys.count > 0) {
        [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:FORUM_DELETE_URL_PATH,[dic objectForKey:@"ID"],model.UserID] view:nil success:^(id json) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            if ([json[@"ret_code"] integerValue]==0) {
                if (_finishBlock) {
                    _finishBlock(@"deleteForum",_dataDic);
                }
                [self back];
            }else {
                [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
            }
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }];
    }
}

#pragma mark - 网页加载
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //获取页面高度（像素）
    NSString * clientheight_str = [webView stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"];
    float clientheight = [clientheight_str floatValue];
    //设置到WebView上
    webView.frame = CGRectMake(0, 120*PERCEN, webView.width, clientheight);
    if (ISIPAD) {
        webView.frame = CGRectMake(460*PERCEN, 140*PERCEN, webView.width, clientheight);
    }
    //获取WebView最佳尺寸（点）
    CGSize frame = [webView sizeThatFits:webView.frame.size];
    //获取内容实际高度（像素）
    NSString * height_str= [webView stringByEvaluatingJavaScriptFromString: @"document.getElementById('webview_content_wrapper').offsetHeight + parseInt(window.getComputedStyle(document.getElementsByTagName('body')[0]).getPropertyValue('margin-top'))  + parseInt(window.getComputedStyle(document.getElementsByTagName('body')[0]).getPropertyValue('margin-bottom'))"];
    CGFloat height = [height_str floatValue];
    //内容实际高度（像素）* 点和像素的比
    height = height * frame.height / clientheight;
    //再次设置WebView高度（点）
    webView.frame = CGRectMake(0, 120*PERCEN, webView.width, height);
    if (ISIPAD) {
          webView.frame = CGRectMake(460*PERCEN, 160*PERCEN, webView.width, height);
    }
    UIScrollView *tempView = (UIScrollView *)[_webView.subviews objectAtIndex:0];
    tempView.scrollEnabled = NO;
    _bottomView.top = 120*PERCEN + height;
    
    if (ISIPAD) {
        _bottomView.top = 160*PERCEN + height;
    }
    _scrollView.height = _bottomView.bottom;
    _scrollView.contentSize = CGSizeMake(_scrollView.width, _scrollView.height);
    _tableView.tableHeaderView = _scrollView;
    
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:( NSError *)error
{
    _webView.height = 0;
    _bottomView.top = 120*PERCEN;
    if (ISIPAD) {
        _bottomView.top = 160*PERCEN;
    }
    _scrollView.height = _bottomView.bottom;
    _scrollView.contentSize = CGSizeMake(_scrollView.width, _scrollView.height);
    _tableView.tableHeaderView = _scrollView;
}

#pragma mark - 表
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _mutArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"MBForumDetailCell";
    MBForumDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[MBForumDetailCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.delegate = self;
    }
    
    if (_mutArr.count > indexPath.row) {
        cell.forumUserID = [_dataDic objectForKey:@"UserID"];
        cell.dataDic = [_mutArr objectAtIndex:indexPath.row];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_mutHeightArr.count > indexPath.row) {
        return [[_mutHeightArr objectAtIndex:indexPath.row]floatValue];
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0*PERCEN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (![UserManager standerDefult].userModel.UserID) {
        MBLoginController *registerLastVC = [[MBLoginController alloc] init];
        registerLastVC.formBaseViewCtrl = NSStringFromClass([self class]);
        [self.navigationController pushViewController:registerLastVC animated:YES];
        return;
    }
    
    if (_mutArr.count > indexPath.row) {
        UserModel *model = [UserManager standerDefult].userModel;
        
        NSDictionary *dictionary = [_mutArr objectAtIndex:indexPath.row];
        //不能回复自己的评论
        NSString *userID = [dictionary objectForKey:@"UserID"];
        if ([userID intValue] == [model.UserID intValue]) {
//            return;
        }
        
        //查询是否有回复信息
        NSDictionary *dic = [dictionary objectForKey:@"ReplyInfo"];
        if ([dic isKindOfClass:[NSDictionary class]]) {
            if (dic.allKeys.count == 0) {
                //第一个回复的人 屌丝啊
                [_replyMutDic removeAllObjects];
                [_replyMutDic addEntriesFromDictionary:dictionary];

                //响应键盘
                if (_inputField) {
                    _emojiView.alpha = 0;
                    [_inputField becomeFirstResponder];
                }

            } else {
                //已有回复了 开始搭建楼层 占楼了
                //回复的人和选中的楼层回复人不能一致
                NSString *UserID = [dic objectForKey:@"UserID"];
//                if ([model.UserID intValue] != [UserID intValue]) {
                    [_replyMutDic removeAllObjects];
                    [_replyMutDic addEntriesFromDictionary:dictionary];
                    
                    //响应键盘
                    if (_inputField) {
                        _emojiView.alpha = 0;
                        [_inputField becomeFirstResponder];
                    }
//                }
            }
        }
    }
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    int lengthCount = (int)(textField.text.length + string.length);
    if (lengthCount >= 101) {
        return NO;
    }
    return YES;
}

#pragma mark - Emoji
- (void)onSelectItemForEmojiView:(NSString *)emoji withView:(EmojiView *)view
{
    if ([emoji isKindOfClass:[NSString class]]) {
        if (emoji.length > 0) {
            _inputField.text = [NSString stringWithFormat:@"%@%@",_inputField.text,emoji];
        }
    }
}

@end
